import React from "react";
import { HomeOutlined, LoginOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import { type MenuProps, Dropdown, Avatar } from "antd";
import { useNavigate } from "react-router";
import { useShallow } from "zustand/react/shallow";
import { modal, message } from "@/hooks/modules/useToast";
import { useUserStore } from "@/store/user";
import { useMenuStore } from "@/store/menus";
import { removeCookieToken } from "@/utils/cookies";

const AvatarIcon: React.FC = () => {
  const { userInfo, clearUserInfo } = useUserStore(useShallow((state) => ({ userInfo: state.userInfo, clearUserInfo: state.clearUserInfo })));
  const { clearAuthMenu } = useMenuStore(useShallow((state) => ({ clearAuthMenu: state.clearAuthMenu })));

  const navigate = useNavigate();

  const logout = () => {
    modal.confirm({
      title: "温馨提示 🧡",
      icon: <ExclamationCircleOutlined />,
      content: "是否确认退出登录？",
      okText: "确认",
      cancelText: "取消",
      maskClosable: true,
      onOk: () => {
        removeCookieToken();
        clearUserInfo();
        clearAuthMenu();
        navigate("/login", { replace: true });
        message.success("退出登录成功！").then(() => {});
      }
    });
  };

  const style = { fontSize: "14px" };

  const items: MenuProps["items"] = [
    {
      key: "1",
      label: <span className="dropdown-item">首页</span>,
      icon: <HomeOutlined style={style} />,
      onClick: () => navigate("/home")
    },
    {
      type: "divider"
    },
    {
      key: "4",
      label: <span className="dropdown-item">退出登录</span>,
      icon: <LoginOutlined style={style} />,
      onClick: logout
    }
  ];

  return (
    <React.Fragment>
      <Dropdown menu={{ items }} trigger={["click"]} placement="bottomLeft" arrow>
        <Avatar className="avatar" size={42} draggable={false} src={userInfo?.avatar} />
      </Dropdown>
    </React.Fragment>
  );
};

export default AvatarIcon;
